package com.kollway.imageselector.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kollway.imageselector.AlbumBitmapCacheHelper;
import com.kollway.imageselector.AlbumBitmapCacheHelper.ILoadImageCallback;
import com.kollway.imageselector.R;
import com.kollway.imageselector.activity.PictureSelectorActivity.PicItem;
import com.kollway.imageselector.view.HackyViewPager;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

import static com.kollway.imageselector.activity.PictureSelectorActivity.SP_PICTURE_SELECTOR_DATA;

/**
 * Created by chenxiabin on 04/11/2016.
 * 预览图片页面
 */

public class PicturePreviewActivity extends Activity {
    private TextView mIndexTotal;
    private View mWholeView;
    private View mToolbarTop;
    private View mToolbarBottom;
    private ImageButton mBtnBack;
    private Button mBtnSend;
    private CheckButton mUseOrigin;
    private CheckButton mSelectBox;
    private HackyViewPager mViewPager;
    private ArrayList<PicItem> mItemList;
    private ArrayList<String> mSelectList;
    private int mCurrentIndex;
    private boolean mFullScreen;
    private int selectMax;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(1);
        setContentView(R.layout.ko_picprev_activity);
        if (savedInstanceState != null) {
            mItemList = savedInstanceState.getParcelableArrayList("ItemList");
        }

        initView();
        selectMax = getIntent().getIntExtra(PictureSelectorActivity.SP_PICTURE_SELECTOR_MAX, 9);
        mUseOrigin.setChecked(getIntent().getBooleanExtra("sendOrigin", false));
        mCurrentIndex = getIntent().getIntExtra("index", 0);
        mItemList = PictureSelectorActivity.PicItemHolder.itemList;
        mSelectList = PictureSelectorActivity.PicItemHolder.selectList;
        mIndexTotal.setText(String.format(getResources().getString(R.string.ko_picsel_toolbar_total), new Object[]{Integer.valueOf(mCurrentIndex + 1), Integer.valueOf(mItemList.size())}));
        int result;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWholeView.setSystemUiVisibility(1024);
            result = getSmartBarHeight(this);
            if (result > 0) {
                RelativeLayout.LayoutParams resourceId = (RelativeLayout.LayoutParams) mToolbarBottom.getLayoutParams();
                resourceId.setMargins(0, 0, 0, result);
                mToolbarBottom.setLayoutParams(resourceId);
            }
        }

        result = 0;
        int resourceId1 = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId1 > 0) {
            result = getResources().getDimensionPixelSize(resourceId1);
        }

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(mToolbarTop.getLayoutParams());
        lp.setMargins(0, result, 0, 0);
        mToolbarTop.setLayoutParams(lp);
        mBtnBack.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("sendOrigin", mUseOrigin.getChecked());
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        mBtnSend.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent data = new Intent();

                ArrayList<String> list = mSelectList;
                if (list.size() == 0) {
                    Toast.makeText(PicturePreviewActivity.this, "您还没有选择图片", Toast.LENGTH_SHORT).show();
                    return;
                }

                data.putExtra("sendOrigin", mUseOrigin.getChecked());
                data.putExtra(SP_PICTURE_SELECTOR_DATA, list);
                setResult(1, data);
                finish();
            }
        });
        mUseOrigin.setText(R.string.ko_picprev_origin);
        mUseOrigin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mUseOrigin.setChecked(!mUseOrigin.getChecked());
                if (mUseOrigin.getChecked() && getTotalSelectedNum() == 0) {
                    mSelectBox.setChecked(!mSelectBox.getChecked());
                    updateToolbar();
                }
            }
        });
        mSelectBox.setText(R.string.ko_picprev_select);
        boolean selected = mSelectList.contains((mItemList.get(mCurrentIndex)).uri);
        mSelectBox.setChecked(selected);
        mSelectBox.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!mSelectBox.getChecked() && getTotalSelectedNum() == selectMax) {
                    Toast.makeText(PicturePreviewActivity.this,
                            getResources().getString(R.string.ko_picsel_selected_max,
                                    new Object[]{Integer.valueOf(selectMax)}), Toast.LENGTH_SHORT).show();
                } else {
                    boolean select = !mSelectBox.getChecked();
                    mSelectBox.setChecked(select);
                    if (select) {
                        mSelectList.add((mItemList.get(mCurrentIndex)).uri);
                    } else {
                        mSelectList.remove((mItemList.get(mCurrentIndex)).uri);
                    }
                    updateToolbar();
                }
            }
        });
        mViewPager.setAdapter(new PreviewAdapter());
        mViewPager.setCurrentItem(mCurrentIndex);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            public void onPageSelected(int position) {
                mCurrentIndex = position;
                mIndexTotal.setText(String.format(getResources().getString(R.string.ko_picsel_toolbar_total), new Object[]{Integer.valueOf(position + 1), Integer.valueOf(mItemList.size())}));
                boolean selected = mSelectList.contains((mItemList.get(position)).uri);
                mSelectBox.setChecked(selected);
            }

            public void onPageScrollStateChanged(int state) {
            }
        });
        updateToolbar();
    }

    private void initView() {
        mToolbarTop = findViewById(R.id.toolbar_top);
        mIndexTotal = (TextView) findViewById(R.id.index_total);
        mBtnBack = (ImageButton) findViewById(R.id.back);
        mBtnSend = (Button) findViewById(R.id.send);
        mWholeView = findViewById(R.id.whole_layout);
        mViewPager = (HackyViewPager) findViewById(R.id.viewpager);
        mToolbarBottom = findViewById(R.id.toolbar_bottom);
        mUseOrigin = new CheckButton(findViewById(R.id.origin_check), R.drawable.ko_origin_check_nor, R.drawable.ko_origin_check_sel);
        mSelectBox = new CheckButton(findViewById(R.id.select_check), R.drawable.ko_select_check_nor, R.drawable.ko_select_check_sel);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 4) {
            Intent intent = new Intent();
            intent.putExtra("sendOrigin", mUseOrigin.getChecked());
            setResult(-1, intent);
        }

        return super.onKeyDown(keyCode, event);
    }

    private int getTotalSelectedNum() {
        return mSelectList.size();
    }

    private String getTotalSelectedSize() {
        float size = 0.0F;

        for (int totalSize = 0; totalSize < mItemList.size(); ++totalSize) {
            boolean selected = mSelectList.contains((mItemList.get(totalSize).uri));
            if (selected) {
                File file = new File((mItemList.get(totalSize)).uri);
                size += (float) (file.length() / 1024L);
            }
        }

        String var4;
        if (size < 1024.0F) {
            var4 = String.format(getString(R.string.ko_picprev_select_size_k), new Object[]{Float.valueOf(size)});
        } else {
            var4 = String.format(getString(R.string.ko_picprev_select_size_m), new Object[]{Float.valueOf(size / 1024.0F)});
        }

        return var4;
    }

    private void updateToolbar() {
        int selNum = getTotalSelectedNum();
        if (mItemList.size() == 1 && selNum == 0) {
            mBtnSend.setText(R.string.ko_picsel_toolbar_send);
            mUseOrigin.setText(R.string.ko_picprev_origin);
        } else {
            if (selNum == 0) {
                mBtnSend.setText(R.string.ko_picsel_toolbar_send);
                mUseOrigin.setText(R.string.ko_picprev_origin);
            } else if (selNum <= selectMax) {
                mBtnSend.setText(String.format(getResources().getString(R.string.ko_picsel_toolbar_send_num), new Object[]{Integer.valueOf(selNum), Integer.valueOf(selectMax)}));
                mUseOrigin.setText(String.format(getResources().getString(R.string.ko_picprev_origin_size), new Object[]{getTotalSelectedSize()}));
            }
        }
    }

    @TargetApi(11)
    public static int getSmartBarHeight(Context context) {
        try {
            Class e = Class.forName("com.androR.id.internal.R$dimen");
            Object obj = e.newInstance();
            Field field = e.getField("mz_action_button_min_height");
            int height = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(height);
        } catch (Exception var5) {
            var5.printStackTrace();
            return 0;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (mItemList != null && mItemList.size() > 0) {
            outState.putParcelableArrayList("ItemList", mItemList);
        }
        super.onSaveInstanceState(outState);
    }

    private class CheckButton {
        private View rootView;
        private ImageView image;
        private TextView text;
        private boolean checked = false;
        private int nor_resId;
        private int sel_resId;

        CheckButton(View root, @DrawableRes int norId, @DrawableRes int selId) {
            rootView = root;
            image = (ImageView) root.findViewById(R.id.image);
            text = (TextView) root.findViewById(R.id.text);
            nor_resId = norId;
            sel_resId = selId;
            image.setImageResource(nor_resId);
        }

        public void setChecked(boolean check) {
            checked = check;
            image.setImageResource(checked ? sel_resId : nor_resId);
        }

        public boolean getChecked() {
            return checked;
        }

        public void setText(int resId) {
            text.setText(resId);
        }

        public void setText(CharSequence chars) {
            text.setText(chars);
        }

        public void setOnClickListener(View.OnClickListener l) {
            rootView.setOnClickListener(l);
        }
    }

    private class PreviewAdapter extends PagerAdapter {
        private PreviewAdapter() {
        }

        @Override
        public int getCount() {
            return mItemList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            final PhotoView photoView = new PhotoView(container.getContext());
            photoView.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                public void onViewTap(View view, float x, float y) {
                    mFullScreen = !mFullScreen;
                    View decorView;
                    byte uiOptions;
                    if (mFullScreen) {
                        if (Build.VERSION.SDK_INT < 16) {
                            getWindow().setFlags(1024, 1024);
                        } else {
                            decorView = getWindow().getDecorView();
                            uiOptions = 4;
                            decorView.setSystemUiVisibility(uiOptions);
                        }

                        mToolbarTop.setVisibility(View.INVISIBLE);
                        mToolbarBottom.setVisibility(View.INVISIBLE);
                    } else {
                        if (Build.VERSION.SDK_INT < 16) {
                            getWindow().setFlags(1024, 1024);
                        } else {
                            decorView = getWindow().getDecorView();
                            uiOptions = 0;
                            decorView.setSystemUiVisibility(uiOptions);
                        }

                        mToolbarTop.setVisibility(View.VISIBLE);
                        mToolbarBottom.setVisibility(View.VISIBLE);
                    }

                }
            });
            container.addView(photoView, -1, -1);
            String path = mItemList.get(position).uri;
            AlbumBitmapCacheHelper.getInstance().removePathFromShowlist(path);
            AlbumBitmapCacheHelper.getInstance().addPathToShowlist(path);
            Bitmap bitmap = AlbumBitmapCacheHelper.getInstance().getBitmap(path, 0, 0, new ILoadImageCallback() {
                public void onLoadImageCallBack(Bitmap bitmap, String p, Object... objects) {
                    if (bitmap != null) {
                        photoView.setImageBitmap(bitmap);
                    }
                }
            }, new Object[]{Integer.valueOf(position)});
            if (bitmap != null) {
                photoView.setImageBitmap(bitmap);
            } else {
                photoView.setImageResource(R.drawable.ko_grid_image_default);
            }

            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
}
